package com.shy.datasource;

import java.sql.SQLException;

import javax.sql.DataSource;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.atomikos.jdbc.AtomikosDataSourceBean;

import com.mysql.cj.jdbc.MysqlXADataSource;
import com.shy.config.DB2Config;

@Configuration
@MapperScan(basePackages={"com.shy.mapper.db2"}, /*sqlSessionFactoryRef = "sqlSessionFactoryDb2"*/ sqlSessionTemplateRef = "sqlSessionTemplateDb2")
public class DbSessionFactory2 {

	@Bean(name = "db2")
	public DataSource newhomeDbDataSource(@Qualifier("DB2Config") DB2Config db2Config) throws SQLException {
		MysqlXADataSource mysqlXADataSource = new MysqlXADataSource();
		mysqlXADataSource.setUrl(db2Config.getJdbcUrl());
		mysqlXADataSource.setUser(db2Config.getUsername());
		mysqlXADataSource.setPassword(db2Config.getPassword());
		mysqlXADataSource.setPinGlobalTxToPhysicalConnection(true);

		AtomikosDataSourceBean atomikosDataSourceBean = new AtomikosDataSourceBean();
		atomikosDataSourceBean.setXaDataSource(mysqlXADataSource);
		atomikosDataSourceBean.setUniqueResourceName("db2");
		return atomikosDataSourceBean;
	}

	@Bean(name = "sqlSessionFactoryDb2")
	public SqlSessionFactory sqlSessionFactoryDb2(@Qualifier("db2") DataSource dataSource) throws Exception {
		SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
		factoryBean.setDataSource(dataSource);
		return factoryBean.getObject();
	}

	@Bean(name = "sqlSessionTemplateDb2")
	public SqlSessionTemplate sqlSessionTemplateDb2(@Qualifier("sqlSessionFactoryDb2") SqlSessionFactory sqlSessionFactory) throws Exception{
		return new SqlSessionTemplate(sqlSessionFactory);
	}
}
